import java.io.*;
import java.net.*;

import javax.swing.JTextArea;


public class Connect 
{

	public class TCPReader extends Thread
	{
		private DataInputStream DIS = null;		
		private boolean active;
		private JTextArea text;
		public TCPReader(DataInputStream input, JTextArea jt)
		{
			DIS = input;
			active = true;
			text = jt;
		}
		
		public void run()
		{
			
			while(active)
			{
			
				try
				{
					String msg = DIS.readUTF();
					text.append("Received from server : " + msg + "\n");
				}catch(IOException e)
				{
					System.out.println(e);
					active = false;
				}
			}
		}
	}
	
	public void initConnnection(final String src_ip, final int src_port, final String target_ip, final int target_port,final JTextArea jt)
	{	
		CaptureThread ct = new CaptureThread()
		{
			public Object construct()
			{
				try
				{
					DataInputStream DIS = null;
					DataOutputStream DOS = null;
					Socket socket = null;
					BufferedReader keyboardReader = null;
					
					// connect to the server
					try
					{			
						socket = new Socket();
						socket.bind(new InetSocketAddress(src_ip,src_port));
						socket.connect(new InetSocketAddress(target_ip,target_port));
						//Obtain the streams...
						DIS = new DataInputStream(socket.getInputStream());
						DOS = new DataOutputStream(socket.getOutputStream());
						keyboardReader = new BufferedReader(new InputStreamReader(System.in));
					}catch(IOException e)
					{
						jt.append("Problems initialising: "+ e);
						System.exit(1);
					}
					
					try
					{
						//Start the listening thread...
						TCPReader reader = new TCPReader(DIS,jt);
						reader.setDaemon(true);
						reader.start();
						
						String input;
						while(true)
						{
							//read data in from the keyboard
							input = keyboardReader.readLine();
							
							//send data to server
							DOS.writeUTF(input);
						}
					}catch(IOException e)
					{			
					}
					
					try
					{
						socket.close();
					}catch(IOException e)
					{			
					}
				}catch(Exception e){ System.out.println(e); }
				
				return 0;
			}
		};
		ct.start();
		
	}
}
